from fastapi import APIRouter, File, UploadFile
from app.common.utils import some_utility_function, DEST_DIR
import pandas as pd

from fastapi.responses import HTMLResponse
from nbconvert import MarkdownExporter
import nbformat
import os
from pathlib import Path
import json


router = APIRouter()


@router.get("/variable", tags=["common"], description="这是一个获取公共变量的接口")
async def view_variable():
    return {"DEST_DIR": DEST_DIR}


@router.get(
    "/getVariablesInfoByfileFullName", tags=["common"], summary="获取变量概览",description="从excel表格文件中获取变量概览"
)
async def get_variables_info_by_filefullName(filefullName: str):
    # 检查文件是否存在（这里我们假设FastAPI服务器有权限访问该文件路径）
    if not Path(filefullName).exists():      
      return {"error": f"文件 {filefullName} 不存在"}

    # 检查文件扩展名，支持 xlsx 和 csv
    if not Path(filefullName).suffix in [".xlsx", ".csv"]:    
      return {"error":f"不支持的文件类型 {Path(filefullName).suffix}"}
    

    try:
        # 使用 pandas 读取文件的第一行
        if Path(filefullName).suffix == ".xlsx":
            df = pd.read_excel(filefullName, header=None, nrows=1)
        elif Path(filefullName).suffix == ".csv":
            df = pd.read_csv(filefullName, header=None, nrows=1)

        # 获取第一行的数据，并转换为所需的格式
        variables_info = [{"name": col} for col in df.iloc[0].tolist()]

        # FastAPI 会自动将返回的字典或列表转换为 JSON
        return json.dumps(variables_info)
    except Exception as e:
      return {"error":f"读取文件时出错: {str(e)}"}
    


def convert_ipynb_to_md(notebook_content, output_filename):
    """
    将 .ipynb 内容转换为 .md 文件

    参数:
    notebook_content (bytes): .ipynb 文件的内容
    output_filename (str): 输出的 .md 文件路径（包括文件名）
    """
    with open("temp_notebook.ipynb", "wb") as f:
        f.write(notebook_content)

    with open("temp_notebook.ipynb", "r", encoding="utf-8") as f:
        notebook = nbformat.read(f, as_version=4)

    exporter = MarkdownExporter()
    md_content, _ = exporter.from_notebook_node(notebook)

    with open(output_filename, "w", encoding="utf-8") as f:
        f.write(md_content)

    # 清理临时文件
    os.remove("temp_notebook.ipynb")


@router.post("/convert/")
async def upload_and_convert(file: UploadFile = File(...)):
    """
    上传 .ipynb 文件并转换为 .md 文件
    """
    # 确保 E 盘的 md 目录存在
    md_directory = Path("E:/md")
    md_directory.mkdir(parents=True, exist_ok=True)

    # 读取上传的文件内容
    notebook_content = await file.read()

    # 获取上传的文件名（不带扩展名）
    filename = file.filename
    basename, _ = os.path.splitext(filename)

    # 构建输出的 .md 文件路径
    output_filename = md_directory / f"{basename}.md"

    # 调用转换函数
    convert_ipynb_to_md(notebook_content, output_filename)

    return {"message": f"Successfully converted {filename} to {output_filename.name}"}


# 可选：添加一个 HTML 页面用于文件上传（不是必需的，但有助于测试）
@router.get("/convertPage")
async def main():
    content = """  
    <html>
    <body>  
    <h1>Please upload a .ipynb file</h1>  
    <form action="/convert/" enctype="multipart/form-data" method="post">  
        <input name="file" type="file"> 
        <input type="submit" value="convert">  
    </form>  
    </body>
    </html>
    """
    return HTMLResponse(content=content)
